package com.ss.project.xia17user.config.security.code;

import com.ss.project.xia17user.common.redis.RedisUtils;
import com.ss.project.xia17user.config.security.form.LoginAttributesNames;
import lombok.RequiredArgsConstructor;
import org.springframework.util.Assert;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 图片验证码
 * @author xia17
 * @date 2020/9/18 11:31
 */
@RequiredArgsConstructor
public class ImageLoginCodePattern implements LoginCodePattern {

    /** 失效时间 */
    private final int expirationTime;
    private final RedisUtils redisUtils;
    private static final String KEY_PREFIX = "login_image_code:";


    @Override
    public String generateCode(Map<String, String> attributes) {
        String uniqueId = attributes.get(LoginAttributesNames.UNIQUE_ID);
        Assert.hasText(uniqueId,"生成图片验证码时不能没有uniqueId");
        String code = this.randomCode();
        redisUtils.set(KEY_PREFIX + uniqueId , code , expirationTime , TimeUnit.SECONDS);
        return code;
    }

    @Override
    public boolean provingCode(Map<String, String> attributes) {
        String uniqueId = attributes.get(LoginAttributesNames.UNIQUE_ID);
        String codeValue = attributes.get(LoginAttributesNames.CODE);
        Assert.hasText(uniqueId,"验证图片验证码时不能没有uniqueId");
        Assert.hasText(codeValue,"验证码的值不能为空");
        Object code = redisUtils.get(KEY_PREFIX + uniqueId);
        if (code != null){
            redisUtils.del(KEY_PREFIX + uniqueId);
        }
        return codeValue.equals(code);
    }



}
